package com.firewolf.springboot.controller;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileController {

	@RequestMapping("toUpload")
	public String toPage() {
		return "myfile";
	}

	@RequestMapping("/file")
	public String file(List<MultipartFile> file) {
		try {
			for (MultipartFile f : file) {
				FileCopyUtils.copy(f.getInputStream(), new FileOutputStream("files/" + f.getOriginalFilename()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "success";
	}

	@RequestMapping("download")
	public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {

		InputStream is =new FileInputStream("files/pig.png");
		byte[] body = new byte[is.available()];
		is.read(body);

		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Disposition", "attachment;filename=pig.png");

		HttpStatus statusCode = HttpStatus.OK;
		ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
		return response;
	}
}
